package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class Dbutil {
    private static ThreadLocal<Connection> th =new ThreadLocal();
    private static DataSource dataSource;



    static {
        try {
            Properties pro = new Properties();
            InputStream in = Dbutil.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    //获取连接对象
    public static Connection getConnection(){
        Connection con = null;
        try {
            con = th.get();
            if(con==null){
                con = dataSource.getConnection();
                th.set(con);
            }
            return con;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
